package com.thejoyrun.retrofit.http.Interceptor;

import org.json.JSONArray;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * Created by kkmike999 on 2016/5/8.
 *
 * 网络日志输出 拦截器
 */
public class LogInterceptor implements Interceptor {

	@Override
	public okhttp3.Response intercept(Chain chain) throws IOException {
		Request request = chain.request();

		// 请求唯一id
		String requestId = new Random(System.currentTimeMillis()).nextInt(9999) + "";

		logRequest(request, requestId);

		// 请求时间
		long t1 = System.currentTimeMillis();

		int    code   = 0;
		String result = "";

		try {
			okhttp3.Response response = chain.proceed(chain.request());// 真正请求

			code = response.code();

			if (response.body() != null) {
				MediaType contentType = response.body()
				                                .contentType();
				result = response.body()
				                 .string();

				ResponseBody body = ResponseBody.create(contentType, result);
				return response.newBuilder()
				               .body(body)
				               .build();
			} else {
				return response;
			}
		} catch (Exception e) {
			throw e;
		} finally {
			// 打印http结果
			long t2 = System.currentTimeMillis();

			if (code >= 400) {
				//				LogUtils.e(requestId, "[ code=" + code + " , time=" + (t2 - t1) + "ms ]");
				System.out.println(requestId + " : " + "[ code=" + code + " , time=" + (t2 - t1) + "ms ]");
			}

			//			LogUtils.d(requestId, result);
			System.out.println(requestId + " : " + result);
		}
	}

	/**
	 * 打印请求
	 *
	 * @param request
	 * @param requestId
	 */
	private void logRequest(Request request, String requestId) {

		JSONArray logArr = new JSONArray();

		logArr.put(request.method());
		logArr.put(request.url());
		logArr.put(getFormString(request.body()));

		// 打印请求
		//		LogUtils.d(requestId, logArr.toString());
		System.out.println(requestId + " : " + logArr.toString());
	}

	private String getFormString(RequestBody requestBody) {
		if (requestBody instanceof FormBody) {
			FormBody            formBody = (FormBody) requestBody;
			Map<String, String> map      = getFormBodyMap(formBody);

			return map.toString();
		}

		return "";
	}

	/**
	 * post参数map
	 *
	 * @param formBody
	 * @return
	 */
	private Map<String, String> getFormBodyMap(FormBody formBody) {
		Map<String, String> map = new HashMap<>();

		if (formBody != null) {
			for (int i = 0; i < formBody.size(); i++) {
				map.put(formBody.name(i), formBody.value(i));
			}
		}

		return map;
	}
}

